package com.quan.commons.log.utils;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.quan.commons.properties.SystemValueProperties;
import com.quan.commons.utils.JwtUtils;
import com.quan.commons.utils.SpringContextHolder;
import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 系统日志工具类
 * @author L.cm
 */
@UtilityClass
public class SysLogUtils {

    public SysLog getSysLog() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        SysLog sysLog = new SysLog();
        sysLog.setUsername(Objects.requireNonNull(getUsername(request)));
        sysLog.setRemoteAddr(ServletUtil.getClientIP(request));
        sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
        sysLog.setMethod(request.getMethod());
        sysLog.setUserAgent(request.getHeader("user-agent"));
        sysLog.setParams(getUrlParams(request));

        return sysLog;
    }

    public SysLog getSysLogLogin() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        SysLog sysLog = new SysLog();
        sysLog.setRemoteAddr(ServletUtil.getClientIP(request));
        sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
        sysLog.setMethod(request.getMethod());
        sysLog.setUserAgent(request.getHeader("user-agent"));
        sysLog.setParams(getUrlParams(request));
        return sysLog;
    }

    private String getUsername(HttpServletRequest request) {
        final SystemValueProperties properties = SpringContextHolder.getBean(SystemValueProperties.class);
        final String token = request.getHeader("token");
        final String userName = JwtUtils.getUserName(token, properties.getJwt().getSecret());
        return userName;
    }

    private String getUrlParams(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();

        final Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            params.put(name, request.getParameter(name));
        }

        return JSON.toJSONString(params);
    }


}
